import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useStaffStore = defineStore('staff', () => {
  const USER_KEY = 'erppos_staff_users'
  const ROLE_KEY = 'erppos_staff_roles'

  // 权限目录（可扩展）
  const permissionCatalog = [
    { key: 'pos', name: 'POS收银', items: [
      { key: 'pos.sale', name: '开单/收银' },
      { key: 'pos.refund', name: '退货/退款' },
      { key: 'pos.discount', name: '折扣/改价' },
    ]},
    { key: 'inventory', name: '库存', items: [
      { key: 'inventory.view', name: '库存查询' },
      { key: 'inventory.inout', name: '入库/出库' },
      { key: 'inventory.stocktake', name: '盘点' },
      { key: 'inventory.transfer', name: '调拨' },
    ]},
    { key: 'report', name: '报表', items: [
      { key: 'report.view', name: '查看报表' },
      { key: 'report.export', name: '导出报表' },
    ]},
    { key: 'member', name: '会员', items: [
      { key: 'member.view', name: '查看会员' },
      { key: 'member.edit', name: '编辑会员/储值/积分' },
    ]},
    { key: 'settings', name: '系统设置', items: [
      { key: 'settings.manage', name: '系统配置管理' },
    ]},
  ]

  const users = ref([])
  const roles = ref([])

  const persist = () => {
    localStorage.setItem(USER_KEY, JSON.stringify(users.value))
    localStorage.setItem(ROLE_KEY, JSON.stringify(roles.value))
  }

  const initialize = () => {
    const u = localStorage.getItem(USER_KEY)
    const r = localStorage.getItem(ROLE_KEY)
    if (r) roles.value = JSON.parse(r)
    if (u) users.value = JSON.parse(u)
    if (u && r) return
    // 初始角色
    roles.value = [
      { id: 'RL001', name: '店长', description: '拥有全部权限', permissions: permissionCatalog.flatMap(g=>g.items.map(i=>i.key)) },
      { id: 'RL002', name: '收银员', description: '仅收银相关', permissions: ['pos.sale','pos.refund'] },
      { id: 'RL003', name: '仓管', description: '库存相关', permissions: ['inventory.view','inventory.inout','inventory.stocktake','inventory.transfer'] },
    ]
    // 初始员工
    users.value = [
      { id: 'U001', name: '张三', account: 'zhangsan', phone: '13800000001', status: 'enabled', roles: ['RL001'], createdAt: '2024-01-01' },
      { id: 'U002', name: '李四', account: 'lisi', phone: '13800000002', status: 'enabled', roles: ['RL002'], createdAt: '2024-01-08' },
      { id: 'U003', name: '王五', account: 'wangwu', phone: '13800000003', status: 'disabled', roles: ['RL003'], createdAt: '2024-01-10' },
    ]
    persist()
  }

  // 角色 CRUD
  const addRole = (data) => { const item = { id: 'RL' + Date.now(), permissions: [], ...data }; roles.value.unshift(item); persist(); return item }
  const updateRole = (id, data) => { const i = roles.value.findIndex(x=>x.id===id); if(i>-1){ roles.value[i] = { ...roles.value[i], ...data }; persist(); return roles.value[i] } return null }
  const removeRole = (id) => { const i = roles.value.findIndex(x=>x.id===id); if(i>-1){ roles.value.splice(i,1); users.value.forEach(u=>{ u.roles = (u.roles||[]).filter(rid=>rid!==id) }); persist(); return true } return false }

  // 员工 CRUD
  const addUser = (data) => { const item = { id: 'U' + Date.now(), status: 'enabled', roles: [], createdAt: new Date().toISOString().slice(0,10), ...data }; users.value.unshift(item); persist(); return item }
  const updateUser = (id, data) => { const i = users.value.findIndex(x=>x.id===id); if(i>-1){ users.value[i] = { ...users.value[i], ...data }; persist(); return users.value[i] } return null }
  const removeUser = (id) => { const i = users.value.findIndex(x=>x.id===id); if(i>-1){ users.value.splice(i,1); persist(); return true } return false }
  const toggleUserStatus = (id) => { const u = users.value.find(x=>x.id===id); if(u){ u.status = u.status==='enabled'?'disabled':'enabled'; persist(); return u.status } return null }

  // 查询与导出
  const getFilteredUsers = (filters) => {
    const s = (filters.search||'').toLowerCase()
    const roleId = filters.roleId || ''
    return users.value.filter(u => {
      if (s && !(u.name||'').toLowerCase().includes(s) && !(u.account||'').toLowerCase().includes(s) && !(u.phone||'').includes(filters.search)) return false
      if (roleId && !(u.roles||[]).includes(roleId)) return false
      if (filters.status && u.status !== filters.status) return false
      return true
    })
  }
  const exportUsers = (list) => {
    const rows = (list||users.value).map(u => [u.name, u.account, u.phone, u.status, (u.roles||[]).map(id => roles.value.find(r=>r.id===id)?.name||id).join('|'), u.createdAt])
    const headers = ['姓名','账号','电话','状态','角色','创建日期']
    const csv = [headers.join(','), ...rows.map(r=>r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = `员工_${new Date().toISOString().slice(0,10)}.csv`
    a.click()
    URL.revokeObjectURL(a.href)
    return true
  }

  const roleOptions = computed(() => roles.value.map(r => ({ label: r.name, value: r.id })))

  return {
    // 数据
    users, roles, permissionCatalog,
    // 初始化/持久化
    initialize,
    // 角色
    addRole, updateRole, removeRole,
    // 员工
    addUser, updateUser, removeUser, toggleUserStatus,
    // 查询导出
    getFilteredUsers, exportUsers,
    roleOptions,
  }
})


